package ooday04;

public class PolymorphicDemo {
    public static void main(String[] args) {

//演示强转成功的条件:
        /*

        Animal o = new Dog("小黑",2,"黑色");
        Dog g = (Dog)o;//引用o所指向的对象,就是Dog类型
        Swim s = (Swim)o;
        //Fish f = (Fish)o;//运行时会发生ClassCastException类型转换异常
        System.out.println(o instanceof Dog);//true
        System.out.println(o instanceof Swim);//true
        System.out.println(o instanceof Fish);//false
        if(o instanceof Fish){//false
            Fish f = (Fish)o;
        }
        */
//演示向上造型(多态)的第2点应用:


        //Animal o = new Animal();//编译错误,抽象类不能被实例化
        Animal[] animals = new Animal[5];
        animals[0] = new Dog("小黑",1,"黑色");//向上造型
        animals[1] = new Dog("小白",2,"白色");
        animals[2] = new Fish("小红",3,"红色");
        animals[3] = new Fish("小橙",2,"橙色");
        animals[4] = new Chick("小灰",1,"灰色");
        for(int i=0;i<animals.length;i++){
            System.out.println(animals[i].name);
            animals[i].drink();
            animals[i].eat();

            if(animals[i] instanceof Dog){
                Dog dog = (Dog)animals[i];
                dog.lookHome();
            }
            if(animals[i] instanceof Chick){
                Chick chick = (Chick)animals[i];
                chick.layEggs();
            }
            if(animals[i] instanceof Swim){
                Swim s = (Swim)animals[i];
                s.swim();
            }
        }



//演示向上造型(多态)的第1点应用
        /*

        Master master = new Master();
        Dog dog = new Dog("小黑",2,"黑色");
        Chick chick = new Chick("小红",1,"红色");
        Fish fish = new Fish("小金",2,"金色");
        master.feed(dog);   //在传参的同时,系统自动做了向上造型//Animal animal = dog;
        master.feed(chick);
        master.feed(fish);
        */
//演示向上造型
        /*

        Dog o1 = new Dog("小红",1,"红色");//狗是狗
        //o1.name/age/color/drink()/eat()/swim()/lookhome()
        Animal o2 = new Dog("小黄",2,"黄色");//狗是动物
        //哦.name/age/color/drink()/eat()/swim()/lookHome()
        Swim o3 = new Dog("小绿",1,"绿色");//狗会游泳
        //o3.swim();
        */
    }
}
